package com.lijiajia.cloud.common.security.access;

import com.lijiajia.cloud.common.security.access.expression.method.CustomMethodSecurityExpressionHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

import java.util.Collections;
import java.util.List;

/**
 * 配置 全局安全配置
 *
 * @author lijiajia
 * @since 2019-05-31
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AccessSecurityConfiguration {

	@Configuration
	public class ConstConfiguration {
		@Bean
		@ConditionalOnMissingBean(Role.class)
		public Role role() {
			return new Role();
		}

		@Bean
		@ConditionalOnMissingBean(Authority.class)
		public Authority authority() {
			return new Authority();
		}
	}


	@Configuration
	public class MethodSecurityConfiguration {
		private final Role role;

		private final Authority authority;

		public MethodSecurityConfiguration(Role role,
										   Authority authority) {
			this.role = role;
			this.authority = authority;
		}

		/**
		 * 配置 方法安全表达式处理器
		 */
		@Bean
		public List<MethodSecurityExpressionHandler> methodSecurityExpressionHandler() {
			CustomMethodSecurityExpressionHandler expressionHandler = new CustomMethodSecurityExpressionHandler();
			if (role != null) {
				expressionHandler.setRole(role);
			}
			if (authority != null) {
				expressionHandler.setAuthority(authority);
			}
			return Collections.singletonList(expressionHandler);
		}
	}
}
